package com.jswlw.controller.api.wrapper;

import com.alibaba.fastjson.JSON;
import com.jswlw.common.BaseApiResponse;
import com.jswlw.common.BaseException;
import com.jswlw.common.ResponseStatus;
import com.jswlw.controller.api.helper.DevInfoHelper;
import com.jswlw.controller.api.helper.DevUserHelper;
import com.jswlw.controller.api.helper.UserHelper;
import com.jswlw.controller.api.req.user.BindDevRequest;
import com.jswlw.controller.api.resp.*;
import com.jswlw.entity.base.User;
import com.jswlw.entity.biz.*;
import com.jswlw.entity.biz.log.LogDevOpt;
import com.jswlw.entity.biz.log.LogSyncWater;
import com.jswlw.service.base.UserService;
import com.jswlw.service.biz.*;
import com.jswlw.service.biz.log.LogDevOptService;
import com.jswlw.service.biz.log.LogSyncWaterService;
import com.jswlw.service.helper.DevApiHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Component
public class UserWrapper {
    @Autowired
    UserService userService;
    @Autowired
    DistributorService distributorService;
    @Autowired
    DevInfoService devInfoService;
    @Autowired
    DevInfoHelper devInfoHelper;
    @Autowired
    DevUserHelper devUserHelper;
    @Autowired
    DevFilterService devFilterService;
    @Autowired
    FilterInfoService filterInfoService;
    @Autowired
    UserHelper userHelper;
    @Autowired
    LogDevOptService logDevOptService;
    @Autowired
    DevApiHelper devApiHelper;
    @Autowired
    BindRecordService bindRecordService;
    @Autowired
    LogSyncWaterService logSyncWaterService;

    @Transactional(rollbackFor = Exception.class)
    public BaseApiResponse bindDev(BindDevRequest request) {

        User user = userHelper.findUser();
        DevInfo devInfo = devInfoService.find4Id(request.getDevId());

        if (Objects.nonNull(devInfo)) {
            if (devInfo.getBindStatus() == 1) {
                BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "绑定失败，此设备已激活");
            }
//            if (Objects.nonNull(bindRecordService.find4Imei(devInfo.getImei()))) {
//                BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "绑定失败，绑定响应中");
//            }
            devInfo.setUserId(user.getId());
            devInfo.setBindStatus(1);
            devInfo.setDevTypeId(request.getDevTypeId());
            devInfo.setBillTypeId(request.getBillType());
            devInfo.setDistributorId(request.getDistributorId());
            devInfo.setDistributorName(request.getDistributorName());
            devInfo.setName(request.getName());
            devInfo.setUserName(request.getUserName());
            devInfo.setTel(request.getTel());
            devInfo.setAddress(request.getAddress());
            devInfoService.bind(devInfo);

            List<DevFilter> devFilters = devFilterService.find4DevId(devInfo.getId());
            int dyijlxzdz = 0;
            int derjlxzdz = 0;
            int dsanjlxzdz = 0;
            int dsijllzdz = 0;
            int dwujlxzdz = 0;
            for (int i = 0; i < devFilters.size(); i++) {
                DevFilter devFilter = devFilters.get(i);
                FilterInfo filterInfo = filterInfoService.find4Id(devFilter.getFilterId());
                if (devFilter.getSort() == 1) {
                    if (request.getBillType() == 0) {
                        dyijlxzdz = filterInfo.getFlux();
                    } else if (request.getBillType() == 1) {
                        dyijlxzdz = filterInfo.getDuration();
                    } else {
                        dyijlxzdz = filterInfo.getFlux();
                    }
                } else if (devFilter.getSort() == 2) {
                    if (request.getBillType() == 0) {
                        derjlxzdz = filterInfo.getFlux();
                    } else if (request.getBillType() == 1) {
                        derjlxzdz = filterInfo.getDuration();
                    } else {
                        derjlxzdz = filterInfo.getFlux();
                    }
                } else if (devFilter.getSort() == 3) {
                    if (request.getBillType() == 0) {
                        dsanjlxzdz = filterInfo.getFlux();
                    } else if (request.getBillType() == 1) {
                        dsanjlxzdz = filterInfo.getDuration();
                    } else {
                        dsanjlxzdz = filterInfo.getFlux();
                    }
                } else if (devFilter.getSort() == 4) {
                    if (request.getBillType() == 0) {
                        dsijllzdz = filterInfo.getFlux();
                    } else if (request.getBillType() == 1) {
                        dsijllzdz = filterInfo.getDuration();
                    } else {
                        dsijllzdz = filterInfo.getFlux();
                    }
                } else if (devFilter.getSort() == 5) {
                    if (request.getBillType() == 0) {
                        dwujlxzdz = filterInfo.getFlux();
                    } else if (request.getBillType() == 1) {
                        dwujlxzdz = filterInfo.getDuration();
                    } else {
                        dwujlxzdz = filterInfo.getFlux();
                    }
                }
            }

            //绑定套餐
            if (!devApiHelper.bindPricing(
                    devInfo.getImei(),
                    devInfo.getBillTypeId(),
                    dyijlxzdz,
                    derjlxzdz,
                    dsanjlxzdz,
                    dsijllzdz,
                    dwujlxzdz
            )) {
                BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "绑定失败设备可能不在线");
            }

            logDevOptService.add(LogDevOpt.builder()
                    .opt("绑定设备")
                    .imei(devInfo.getImei())
                    .devId(request.getDevId())
                    .createTime(new Date())
                    .createUserId(user.getId())
                    .res(JSON.toJSONString(request))
                    .build());

        } else {
            BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "绑定失败，此ID不存在");
        }

        return BaseApiResponse.of().withResultSuccess();
    }

    public DevInfoResponse devInfo(String devId) {
        DevInfoResponse response = new DevInfoResponse();
        DevInfo devInfo = devInfoService.find4Id(devId);
        DevInfoResponse.DevInfoData data = DevInfoResponse.DevInfoData.builder()
                .id(devInfo.getId())
                .onlineStatus(devInfo.getOnlineStatus())
                .purityTds(devInfo.getPurityTds())
                .rawTds(devInfo.getRawTds())
                .remainFlow(devInfo.getRemainFlow())
                .usedFlow(devInfo.getUsedFlow())
                .remainTime(devInfo.getRemainTime())
                .usedTime(devInfo.getUsedTime())
                .onlineStatus(devInfo.getOnlineStatus())
                .unitFlow(devInfo.getUsedFlow())
                .devTypeId(devInfo.getDevTypeId())
                .billType(devInfo.getBillTypeId())
                .devStatus(devInfo.getDevStatus())
                .distributorId(devInfo.getDistributorId())
                .build();
        response.setData(data);
        response.success();
        return response;
    }

    public DevFilterResponse devFilter(String devId) {
        DevFilterResponse response = new DevFilterResponse();
        DevFilter devFilterFilter = new DevFilter();
        devFilterFilter.setDevId(devId);
        List<DevFilter> devFilterList = devFilterService.queryList(devFilterFilter);

        DevFilterResponse.DevFilterData data = DevFilterResponse.DevFilterData.builder().build();
        data.setDescription("小知识：RO（Reverse Osmosis）反渗透技术是利用渗透压力差为动力的膜分离过滤技术，源于美国二十世纪六十年代宇航科技的研究，后逐渐转化为民用，目前已广泛运用于科研、医药、食品、饮料、 海水淡化等领域");
        List<DevFilterResponse.DevFilterListData> filterListData = new ArrayList<>();
        devFilterList.forEach(devFilter -> {
            DevFilterResponse.DevFilterListData item = DevFilterResponse.DevFilterListData.builder().build();
            FilterInfo filterInfo = filterInfoService.find4Id(devFilter.getFilterId());
            item.setId(devFilter.getId());
            item.setName(filterInfo.getName());
            item.setDescription(filterInfo.getDescription());
            item.setRemain((devFilter.getMaxValue() - devFilter.getUsed()) * 100 / devFilter.getMaxValue());
            item.setSort(devFilter.getSort());
            filterListData.add(item);
        });

        data.setListData(filterListData);
        response.setData(data);
        response.success();
        return response;
    }

    public UserInfoResponse userInfo(String devId) {
        UserInfoResponse response = new UserInfoResponse();
        DevInfo devInfo = devInfoService.find4Id(devId);
        response.setData(UserInfoResponse.UserInfoData.builder()
                .userName(devInfo.getUserName())
                .tel(devInfo.getTel())
                .address(devInfo.getAddress())
                .bindTime(new SimpleDateFormat("yyyy-MM-dd").format(devInfo.getBindTime()))
                .build());
        response.success();
        return response;
    }


    public BaseApiResponse stop(String devId) {
        devInfoService.stop(devId);
        DevInfo devInfo = devInfoService.find4Id(devId);
        logDevOptService.add(LogDevOpt.builder()
                .opt("关机设备")
                .imei(devInfo.getImei())
                .devId(devInfo.getId())
                .createTime(new Date())
                .createUserId(userHelper.findUser().getId())
                .res(devId)
                .build());
        return BaseApiResponse.of().withResultSuccess();
    }

    public BaseApiResponse start(String devId) {
        devInfoService.start(devId);
        DevInfo devInfo = devInfoService.find4Id(devId);
        logDevOptService.add(LogDevOpt.builder()
                .opt("开机设备")
                .imei(devInfo.getImei())
                .devId(devInfo.getId())
                .createTime(new Date())
                .createUserId(userHelper.findUser().getId())
                .res(devId)
                .build());
        return BaseApiResponse.of().withResultSuccess();
    }

    public DistributorResponse distributor(String devId) {
        DistributorResponse response = new DistributorResponse();
        DevInfo devInfo = devInfoService.find4Id(devId);
        Distributor distributor = distributorService.find4Id(devInfo.getDistributorId());
        response.setData(DistributorResponse.DistributorResponseData.builder()
                .id(distributor.getId())
                .name(distributor.getName())
                .linkMan(distributor.getLinkMan())
                .linkTel(distributor.getLinkTel())
                .address(distributor.getAddress())
                .build());
        response.success();
        return response;
    }

    public UserDevInfoListResponse userDevInfoList() {
        UserDevInfoListResponse response = new UserDevInfoListResponse();
        User user = userHelper.findUser();
        DevInfo filter = new DevInfo();
        filter.setUserId(user.getId());
        List<DevInfo> list = devInfoService.queryList(filter);
        List<UserDevInfoListResponse.UserDevInfoListResponseData> data = new ArrayList<>();
        list.forEach(devInfo -> {
            data.add(UserDevInfoListResponse.UserDevInfoListResponseData
                    .builder()
                    .id(devInfo.getId())
                    .name(devInfo.getName())
                    .billType(devInfo.getBillTypeId())
                    .build());
        });
        response.setData(data);
        response.success();
        return response;
    }

    public BaseApiResponse force(String devId) {
        devInfoService.force(devId);
        DevInfo devInfo = devInfoService.find4Id(devId);

        logDevOptService.add(LogDevOpt.builder()
                .opt("强冲设备")
                .imei(devInfo.getImei())
                .devId(devId)
                .createTime(new Date())
                .createUserId(userHelper.findUser().getId())
                .res(devId)
                .build());
        return BaseApiResponse.of().withResultSuccess();
    }

    public WaterInfoResponse waterInfo(String devId) {
        WaterInfoResponse response = new WaterInfoResponse();
        DevInfo devInfo = devInfoService.find4Id(devId);
        LogSyncWater logSyncWater = logSyncWaterService.findLastUsed4Imei(devInfo.getImei());
        response.setData(WaterInfoResponse.WaterInfo
                .builder()
                .devId(devId)
                .unitFlow(Objects.isNull(logSyncWater) ? 0 : Double.valueOf(logSyncWater.getWater() * 0.01))
                .usedFlow(devInfo.getUsedFlow())
                .usedTime(devInfo.getUsedTime())
                .build());
        response.success();
        return response;
    }

    public BaseApiResponse filterInit(String devId, Integer filterId) {
        devInfoService.filterInit(devId, filterId);
        DevInfo devInfo = devInfoService.find4Id(devId);

        logDevOptService.add(LogDevOpt.builder()
                .opt("滤芯初始化")
                .imei(devInfo.getImei())
                .devId(devId)
                .createTime(new Date())
                .createUserId(userHelper.findUser().getId())
                .res(devId)
                .build());
        return BaseApiResponse.of().withResultSuccess();
    }
}
